import React, { PureComponent } from 'react';
import { Table, Select, Button, DatePicker, Input, InputNumber } from "antd";
import moment from 'moment';
import './App.css';

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.data = [
      { id: 1001, name: '张三', sex: '女', pwd: '1234', age: 29, birth: '1992-01-01' },
      { id: 1002, name: '李四', sex: '男', pwd: '1234', age: 29, birth: '1992-01-02' },
      { id: 1003, name: '王五', sex: '女', pwd: '1234', age: 29, birth: '1992-01-03' },
      { id: 1004, name: '赵六', sex: '男', pwd: '1234', age: 29, birth: '1992-01-04' },
    ];
    const options = this.data.map(({ id, name }) => ({ id, name }));
    this.state = {
      data: this.data,
      options,
      selectedRowKeys: [],
      selectedRows: [],
      edit: false,
    };
  }

  handleClick = (type) => {
    const { data, selectedRowKeys } = this.state;
    switch (type) {
      case "add":
        const last = data[data.length - 1] || {};
        const id = (last.id || 1000) + 1;
        this.setState({
          data: [
            ...data,
            {
              id,
            }
          ],
          selectedRowKeys: [...selectedRowKeys, id],
        })
        break;
      case "delete":
        const newData = data.filter(item => !selectedRowKeys.includes(item.id));
        this.setState({ data: newData });
        break;
      case "edit":
        this.setState({ edit: true });
        break;
      case "query":
        break;
      case "submit":
        this.setState({ selectedRowKeys: [] });
        break;
    }
  }

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  }

  onSelect = (v) => {
    this.setState({ data: this.data }, () => {
      const data = this.state.data.filter(item => item.id === v);
      this.setState({ data });
    });
  }

  onClear = () => {
    this.setState({ data: this.data });
  }

  filterOption = (input, options) => {
    return `${options.value}` === `${input}` || `${input}` === `${options.children}`;
  }

  onChange = (fieldName, id, value) => {
    const data = this.state.data.map(item => {
      if (id === item.id) {
        let birth = item.birth;
        if (fieldName === 'birth') {
          birth = moment(value).format('YYYY-MM-DD');
        }
        return {
          ...item,
          [fieldName]: value,
          birth,
        };
      }
      return item;
    });
    this.setState({ data });
  }

  columns = () => {
    const { selectedRowKeys } = this.state;
    return [{
      title: '工号',
      dataIndex: 'id',
      width: 150,
    }, {
      title: '姓名',
      dataIndex: 'name',
      width: 150,
      render: (name, row, key) => {
        if (selectedRowKeys.includes(row.id)) {
          return <Input defaultValue={name} onChange={e => this.onChange('name', row.id, e.target.value || '')}/>;
        }
        return name;
      }
    }, {
      title: '性别',
      dataIndex: 'sex',
      width: 150,
      render: (sex, row) => {
        if (selectedRowKeys.includes(row.id)) {
          return (
            <Select value={sex} onChange={v => this.onChange('sex', row.id, v)} style={{ width: '100%' }}>
              <Select.Option value="男">男</Select.Option>
              <Select.Option value="女">女</Select.Option>
            </Select>
          )
        }
        return sex;
      }
    }, {
      title: '密码',
      dataIndex: 'pwd',
      width: 150,
      render: (pwd, row, key) => {
        if (selectedRowKeys.includes(row.id)) {
          return <Input defaultValue={pwd} onChange={e => this.onChange('pwd', row.id, e.target.value || '')}/>;
        }
        return pwd;
      }
    }, {
      title: '年龄',
      dataIndex: 'age',
      width: 150,
      render: (age, row, key) => {
        if (selectedRowKeys.includes(row.id)) {
          return <InputNumber defaultValue={age} onChange={v => this.onChange('age', row.id, v)}
                              style={{ width: '100%' }}/>;
        }
        return age;
      }
    }, {
      title: '出生日期',
      dataIndex: 'birth',
      width: 150,
      render: (birth, row, key) => {
        if (selectedRowKeys.includes(row.id)) {
          return <DatePicker defaultValue={moment(birth)} onChange={v => this.onChange('birth', row.id, v)}/>
        }
        return birth;
      }
    }]
  }

  render() {
    const { data, options, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    return (
      <div className="container">
        <header>
          <Button className="btns" onClick={() => this.handleClick('add')}>新增</Button>
          <Button className="btns" onClick={() => this.handleClick('delete')}>删除</Button>
          <Button className="btns" onClick={() => this.handleClick('submit')}>保存</Button>
          <Select
            className="select"
            placeholder="按工号/姓名查询"
            showSearch
            onSelect={this.onSelect}
            onClear={this.onClear}
            filterOption={this.filterOption}
            allowClear
          >
            {options.map((item, key) => <Select.Option key={key} value={item.id}>{item.name}</Select.Option>)}
          </Select>
        </header>
        <Table
          rowKey="id"
          className="table"
          dataSource={data}
          columns={this.columns()}
          rowSelection={rowSelection}
        />
      </div>
    )
  }
}

export default App;
